package monster.comm.util;

import java.util.List;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import monster.comm.log.ILog;
import monster.comm.log.LogService;

/**
 * 创建======
 * @author wanghong 2012-12-19 MyBatisDaoSupport.java
 * @see mybatis批量插入类
 * @date 
 * 
 * 修改===========
 * 
 * 
 */


public class MyBatisBatchInsertSupport {
	private static final int defaultDoFlushSize = 500;
	private static ILog  log = LogService.getLog(MyBatisBatchInsertSupport.class);
	private SqlSessionFactory sqlSessionFactory;

	public SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	/**
	 * 批量插入数据
	 * 
	 * @param method
	 *            全路径方法名
	 * @param list
	 *            实体类List
	 * @throws Exception
	 */
	public void batchInsert(String method, List<?> list) {
		// 从当前环境中生成批量提交的sqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession(
				ExecutorType.BATCH, false);//自动提交为false
		int startFlushRowIndex = 1;
		long start_time = System.currentTimeMillis();
		for (int index = 0; index < list.size(); index++) {
			// 插入对象
			sqlSession.insert(method, list.get(index));
			if (startFlushRowIndex++ == defaultDoFlushSize) {
				sqlSession.flushStatements();
				sqlSession.clearCache();
			}
		}
		sqlSession.flushStatements();
		sqlSession.clearCache();
		long end_time = System.currentTimeMillis();
		long dif_time = (end_time-start_time)/1000;
		log.info("消耗时间"+dif_time+"秒");
	}
	/**
	 * 批量修改数据
	 * 
	 * @param method
	 *            全路径方法名
	 * @param list
	 *            实体类List
	 * @throws Exception
	 */
	public void batchUpdate(String method, List<?> list) {
		// 从当前环境中生成批量提交的sqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession(
				ExecutorType.BATCH, false);//自动提交为false
		int startFlushRowIndex = 1;
		long start_time = System.currentTimeMillis();
		for (int index = 0; index < list.size(); index++) {
			// 修改对象
			sqlSession.update(method, list.get(index));
			if (startFlushRowIndex++ == defaultDoFlushSize) {
				sqlSession.flushStatements();
				sqlSession.clearCache();
			}
		}
		sqlSession.flushStatements();
		sqlSession.clearCache();
		long end_time = System.currentTimeMillis();
		long dif_time = (end_time-start_time)/1000;
		log.info("消耗时间"+dif_time+"秒");
	}
}
